<template>
  <div class="register">
    <van-nav-bar title="嗨购商城" left-arrow @click-left="onClickLeft" />

    <van-form @submit="onSubmit">
      <van-cell-group>
        <van-field v-model="code" name="code" placeholder="请输入您的验证码..">
          <template #button>
            <van-button
              type="primary"
              :disabled="flag"
              color="red"
              size="small"
              @click="sendMsg"
              >{{ text }}</van-button
            >
          </template>
        </van-field>
      </van-cell-group>
      <div style="margin: 16px">
        <van-button round block color="red" native-type="submit">
          提交
        </van-button>
      </div>
    </van-form>
  </div>
</template>
<script setup>
import { ref, computed } from "vue";
import { useRouter } from "vue-router";
import { dosendmsgcode,docheckcode } from "@/api/user.js";
const router = useRouter();
const onClickLeft = () => history.back();
const code = ref("");
const flag = ref(false);
const text = ref("发送验证码");
const time = ref(60);

let timer = null;
const countDown = () => {
  time.value--;
  if (time.value <= 0) {
    text.value = "发送验证码";
    flag.value = false;
    clearInterval(timer);
  } else {
    text.value = `${time.value}s后重新发送`;
    flag.value = true;
  }
};
// 点击发送验证码按钮
const sendMsg = () => {
  countDown();
  timer = setInterval(() => {
    countDown(timer);
  }, 1000);

  dosendmsgcode({ tel: localStorage.getItem("tel") }).then(({ data: res }) => {
    // console.log(res.data);
    code.value = res.data
  });  
};
// 点击提交提交按钮
const onSubmit = (suer) => {
 docheckcode({tel:localStorage.getItem("tel"),telcode:code.value}).then(({data:res})=>{
    // console.log(res);
    if (res.code==10007) {
          showFailToast("验证码错误");
          return;
    }

    router.push("/register/pass")
    
 })
};
</script>

<style>
</style>